import sys
import logging
from pathlib import Path
from sqlalchemy import inspect
from sqlalchemy.exc import SQLAlchemyError

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

from app.db.session import SessionLocal, engine
from app.models import user
from app.core.config import settings
from app.crud.user import user_crud
from app.schemas.user import UserCreate
from app.models.user import User

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def check_database() -> bool:
    """检查数据库表和记录"""
    try:
        inspector = inspect(engine)
        tables = inspector.get_table_names()
        logger.info(f"数据库中的表: {tables}")
        
        if "user" in tables:
            logger.info("user 表已存在")
            
            # 检查表中的记录数
            db = SessionLocal()
            try:
                user_count = db.query(User).count()
                logger.info(f"user 表中有 {user_count} 条记录")
                
                if user_count > 0:
                    users = db.query(User).all()
                    for user in users:
                        logger.info(f"用户ID: {user.id}, 用户名: {user.username}, 邮箱: {user.email}, 是否超级用户: {user.is_superuser}")
            finally:
                db.close()
            return True
        else:
            logger.info("user 表不存在")
            return False
    except SQLAlchemyError as e:
        logger.error(f"检查数据库时发生错误: {str(e)}")
        return False

def init_db() -> None:
    """初始化数据库：创建表和超级用户"""
    logger.info("检查数据库状态...")
    tables_exist = check_database()
    
    if not tables_exist:
        logger.info("正在创建表...")
        try:
            # 创建数据库表
            user.Base.metadata.create_all(bind=engine)
            logger.info("数据库表创建完成")
        except SQLAlchemyError as e:
            logger.error(f"创建数据库表时发生错误: {str(e)}")
            return
    
    logger.info("检查超级用户...")
    db = SessionLocal()
    try:
        # 创建超级用户
        superuser = user_crud.get_by_username(db, username=settings.FIRST_SUPERUSER)
        if not superuser:
            user_in = UserCreate(
                username=settings.FIRST_SUPERUSER,
                email=settings.FIRST_SUPERUSER_EMAIL,
                password=settings.FIRST_SUPERUSER_PASSWORD,
                is_superuser=True,
            )
            try:
                superuser = user_crud.create(db, obj_in=user_in)
                logger.info(f"超级用户 {superuser.username} 创建成功")
            except Exception as e:
                logger.error(f"创建超级用户时发生错误: {str(e)}")
        else:
            logger.info(f"超级用户 {superuser.username} 已存在")
    except SQLAlchemyError as e:
        logger.error(f"检查超级用户时发生错误: {str(e)}")
    finally:
        db.close()

if __name__ == "__main__":
    logger.info("初始化数据库...")
    init_db()
    logger.info("数据库初始化完成")